<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket连接测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 600px;
            margin: 20px auto;
            padding: 20px;
        }
        button {
            margin: 10px 5px;
            padding: 10px 20px;
            font-size: 16px;
        }
        .log {
            margin: 10px 0;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            white-space: pre-wrap;
            max-height: 400px;
            overflow-y: auto;
            background: #f9f9f9;
        }
        .success { color: green; }
        .error { color: red; }
        .info { color: blue; }
    </style>
</head>
<body>
    <h1>🔌 WebSocket连接测试</h1>
    
    <div>
        <button onclick="connectWebSocket()">连接WebSocket</button>
        <button onclick="sendTestMessage()">发送测试消息</button>
        <button onclick="disconnectWebSocket()">断开连接</button>
        <button onclick="clearLog()">清空日志</button>
    </div>
    
    <div>
        <strong>连接状态：</strong>
        <span id="status">未连接</span>
    </div>
    
    <div id="log" class="log">等待操作...</div>

    <script>
        const WS_URL = 'ws://localhost:8123/ws/voice-chat';
        let ws = null;
        
        function log(message, type = 'info') {
            const logDiv = document.getElementById('log');
            const timestamp = new Date().toLocaleTimeString();
            const logEntry = `[${timestamp}] ${message}\n`;
            
            const span = document.createElement('span');
            span.className = type;
            span.textContent = logEntry;
            
            logDiv.appendChild(span);
            logDiv.scrollTop = logDiv.scrollHeight;
        }
        
        function updateStatus(status) {
            document.getElementById('status').textContent = status;
        }
        
        function connectWebSocket() {
            if (ws && ws.readyState === WebSocket.OPEN) {
                log('WebSocket已经连接', 'info');
                return;
            }
            
            log('正在连接WebSocket...', 'info');
            updateStatus('连接中...');
            
            try {
                ws = new WebSocket(WS_URL);
                
                ws.onopen = (event) => {
                    log('✅ WebSocket连接成功', 'success');
                    updateStatus('已连接');
                };
                
                ws.onmessage = (event) => {
                    try {
                        const data = JSON.parse(event.data);
                        log(`📥 收到消息: ${JSON.stringify(data, null, 2)}`, 'success');
                    } catch (error) {
                        log(`📥 收到原始消息: ${event.data}`, 'info');
                    }
                };
                
                ws.onclose = (event) => {
                    log(`🔌 WebSocket连接关闭，代码: ${event.code}, 原因: ${event.reason || '无'}`, 'info');
                    updateStatus('已断开');
                    ws = null;
                };
                
                ws.onerror = (error) => {
                    log(`❌ WebSocket错误: ${error}`, 'error');
                    updateStatus('连接错误');
                };
                
            } catch (error) {
                log(`❌ 创建WebSocket失败: ${error.message}`, 'error');
                updateStatus('创建失败');
            }
        }
        
        function sendTestMessage() {
            if (!ws || ws.readyState !== WebSocket.OPEN) {
                log('❌ WebSocket未连接，无法发送消息', 'error');
                return;
            }
            
            const testMessage = {
                textInput: 'WebSocket测试消息',
                sessionId: 'ws-test-' + Date.now()
            };
            
            try {
                ws.send(JSON.stringify(testMessage));
                log(`📤 发送消息: ${JSON.stringify(testMessage, null, 2)}`, 'info');
            } catch (error) {
                log(`❌ 发送消息失败: ${error.message}`, 'error');
            }
        }
        
        function disconnectWebSocket() {
            if (ws) {
                ws.close();
                log('主动断开WebSocket连接', 'info');
            } else {
                log('WebSocket未连接', 'info');
            }
        }
        
        function clearLog() {
            document.getElementById('log').innerHTML = '';
        }
        
        // 页面加载时自动尝试连接
        window.addEventListener('load', () => {
            log('页面加载完成，准备测试WebSocket连接', 'info');
        });
    </script>
</body>
</html>
